package chatNetwork;

import java.awt.Color;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;

import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.JTextPane;
import javax.swing.SwingConstants;
import javax.swing.border.EmptyBorder;

public class MultiChatServer extends JFrame implements Runnable {
	
	ServerSocket server;
	Socket client;
	boolean tFlag; // thread의 반복여부
	StringBuilder data = new StringBuilder();
	MultiChatServerThread mcst;
	HashMap<String, MultiChatServerThread> clients =  new HashMap<String, MultiChatServerThread>();

	private JPanel contentPane;
	private JButton btnEnd;
	private JButton btnStart;
	private JScrollPane scrollPane;
	private JScrollPane scrollPane_1;
	private JList memList;
	private JTextPane result;
	private JComboBox comboBox;
	private JTextField msgIn;
	private JButton btnSend;
	private JLabel lblUserList_1;
	private JLabel lblChatRoom_1;

	public static void main(String[] args) {
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
					MultiChatServer frame = new MultiChatServer();
					frame.setVisible(true);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}
	
	public MultiChatServer() {		
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setBounds(100, 100, 750, 400);
		contentPane = new JPanel();
		contentPane.setBackground(Color.PINK);
		contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
		setContentPane(contentPane);
		contentPane.setLayout(null);
		contentPane.add(getBtnEnd());
		contentPane.add(getBtnStart());
		contentPane.add(getScrollPane());
		contentPane.add(getScrollPane_1());
		contentPane.add(getComboBox());
		contentPane.add(getMsgIn());
		contentPane.add(getBtnSend());
		try{
			InetAddress ia = InetAddress.getLocalHost(); // 주소를 가져와 타이틀을 IP주소로 변경해준다.			
			setTitle("IP Address: " + ia.getHostAddress() + ", Port Number : 4444");
		}catch(Exception ei){
			ei.printStackTrace();
		}
		
	}

	@Override
	public void run() {
		try {
			server = new ServerSocket(4444);			
			tFlag=true;
			Date d = new Date();
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh-mm-ss");
			dataSet("<hr/>");
			dataSet("<font size='4' color='#6a5acd'><b>서버가 시작됨</b></font><br/>" + "서버시작시간 : " + sdf.format(d));
			dataSet("<hr/>");
			
			while(tFlag){
				client = server.accept();
				
				InputStream is = client.getInputStream();
				ObjectInputStream ois = new ObjectInputStream(is);
				
				SocketData sd = (SocketData)ois.readObject();
				dataSet(sd);
				mcst = new MultiChatServerThread(this, client);
				clients.put(sd.getUser(), mcst);
				
				ois.close();is.close();
				
			}
			
			
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
	public void serverStart(){
		
		Thread t = new Thread(this);
		t.start();
		
		btnStart.setEnabled(false);
		btnEnd.setEnabled(true);		
		
	}
	public void serverStop(){
		
	}
	public void sendMsg(){
		
	}
	/* JTextPane에 문자열을 추가하기 위해서
	 * StringBuilder 에 매개변수로 입력된 문자열을 추가(append) 
	 * StringBuilder 에 "<br/>" 추가, 줄바꿈을 하기 위함.
	 * JTextPane의 setText()를 사용하여 문자열 설정.
	 */	
	public void dataSet(SocketData b){ 
			
		data.append(b.getUser() + " : " + b.getMessage() + "<br/>");
		result.setText(data.toString());

	}
	public void dataSet(String a){ 
			
		data.append(a + "<br/>");
		result.setText(data.toString());

	}
	private JButton getBtnEnd() {
		if (btnEnd == null) {
			btnEnd = new JButton("Server End");
			btnEnd.setEnabled(false);
			btnEnd.setBackground(Color.PINK);
			btnEnd.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent e) {
					serverStop();
				}
			});
			btnEnd.setBounds(612, 10, 110, 23);
		}
		return btnEnd;
	}
	private JButton getBtnStart() {
		if (btnStart == null) {
			btnStart = new JButton("Server Start");
			btnStart.setBackground(Color.PINK);
			btnStart.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent e) {
					serverStart();
				}
			});
			btnStart.setBounds(490, 10, 110, 23);
		}
		return btnStart;
	}
	private JButton getBtnSend() {
		if (btnSend == null) {
			btnSend = new JButton("Send");
			btnSend.setBackground(Color.PINK);
			btnSend.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent e) {
					sendMsg();
				}
			});
			btnSend.setBounds(625, 328, 97, 23);
		}
		return btnSend;
	}
	private JScrollPane getScrollPane() {
		if (scrollPane == null) {
			scrollPane = new JScrollPane();
			scrollPane.setBounds(12, 43, 211, 275);
			scrollPane.setViewportView(getMemList());
			scrollPane.setColumnHeaderView(getLblUserList_1());
		}
		return scrollPane;
	}
	private JScrollPane getScrollPane_1() {
		if (scrollPane_1 == null) {
			scrollPane_1 = new JScrollPane();
			scrollPane_1.setBounds(235, 43, 487, 275);
			scrollPane_1.setViewportView(getResult());
			scrollPane_1.setColumnHeaderView(getLblChatRoom_1());
		}
		return scrollPane_1;
	}
	private JList getMemList() {
		if (memList == null) {
			memList = new JList();
			memList.setBackground(Color.WHITE);
		}
		return memList;
	}
	private JTextPane getResult() {
		if (result == null) {
			result = new JTextPane();
			result.setBackground(Color.WHITE);
			result.setContentType("text/html");
		}
		return result;
	}
	private JComboBox getComboBox() {
		if (comboBox == null) {
			comboBox = new JComboBox();
			comboBox.setBackground(Color.PINK);
			comboBox.setBounds(12, 328, 103, 23);
		}
		return comboBox;
	}
	private JTextField getMsgIn() {
		if (msgIn == null) {
			msgIn = new JTextField();
			msgIn.addKeyListener(new KeyAdapter() {
				@Override
				public void keyPressed(KeyEvent e) {
					int a = e.getKeyCode();
					if(a == e.VK_ENTER){
						sendMsg();
					}
				}
			});
			msgIn.setBackground(Color.PINK);
			msgIn.setText("Message");
			msgIn.setBounds(127, 329, 487, 22);
			msgIn.setColumns(10);
		}
		return msgIn;
	}
	
	private JLabel getLblUserList_1() {
		if (lblUserList_1 == null) {
			lblUserList_1 = new JLabel("User List");
			lblUserList_1.setOpaque(true);
			lblUserList_1.setBackground(Color.WHITE);
			lblUserList_1.setHorizontalAlignment(SwingConstants.CENTER);
		}
		return lblUserList_1;
	}
	private JLabel getLblChatRoom_1() {
		if (lblChatRoom_1 == null) {
			lblChatRoom_1 = new JLabel("Chat Room");
			lblChatRoom_1.setOpaque(true);
			lblChatRoom_1.setBackground(Color.WHITE);
			lblChatRoom_1.setHorizontalAlignment(SwingConstants.CENTER);
		}
		return lblChatRoom_1;
	}
}
